package com.protocols.sctp;

import java.io.DataOutputStream;
import java.io.IOException;
import java.rmi.AccessException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.Registry;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.sun.nio.sctp.MessageInfo;
import com.sun.nio.sctp.SctpChannel;

import java.nio.ByteBuffer;
import com.protocols.GeneralProtocolData;
import com.protocols.ProtoOperations;
import com.protocols.sctp.m3ua.M3uaHandlerInterface;

public class TreatInCommingSctp extends Thread {

	private byte [] input;
	private Logger Log;
	private SctpChannel outToServer;
	private M3uaHandlerInterface M3uaHandler;
	private long SessionID=0;
	private Boolean logInfoEnabled=false;
	
	public TreatInCommingSctp(byte [] input, M3uaHandlerInterface m3uaHandler, SctpChannel outToServer, Logger log, long sessionid) {
		this.input=input;
		this.M3uaHandler=m3uaHandler;
		this.outToServer=outToServer;
		this.Log=log;
		SessionID=sessionid;
		logInfoEnabled=Log.isLoggable(Level.INFO);	
	}

    public void run()
    {    	
        // call the remote method
    	try {
    		if(logInfoEnabled)Log.info(SessionID+":Handing Over to M3uaHandler :"+ProtoOperations.getHexString(input));
    		GeneralProtocolData response=(GeneralProtocolData)M3uaHandler.sctpToM3ua(SessionID,input);
			if(response==null)
			{
			}
			else
			{
				if(logInfoEnabled)Log.info(SessionID+":Response Received from M3UA. Writing to the Sctp");
	    		
				final ByteBuffer byteBuffer = ByteBuffer.allocate(9000);            
	            byte [] message = response.getByteArray();
	            final MessageInfo messageInfo = MessageInfo.createOutgoing(null, 0);            
	            messageInfo.payloadProtocolID(3);           
	            byteBuffer.put(message);
	            byteBuffer.flip();
	            
	            outToServer.send(byteBuffer, messageInfo);
	            
			}
			
		} catch ( Exception e) {
			Log.warning(SessionID+":Exception Occured :" +e.getClass().getSimpleName()+":"+ Arrays.toString(e.getStackTrace()));

		}
    }
}
